﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using H2.NET.Common;
using System.Data;
using H2.NET.Business.Core;
using H2.NET.DBUtility;
using System.Data.SqlClient;

namespace H2.NET.Web.Workflow.Services
{
    public partial class PermissionService
    {
        public PermissionService()
        {
            DbHelperSQL.connectionString = PubConstant.ConnectionString;
        }

        #region  BasicMethod
        /// <summary>
        /// 是否存在该记录
        /// </summary>
        public bool Exists(int Id)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) from t_mdc_Permission");
            strSql.Append(" where Id=@Id");
            SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
            parameters[0].Value = Id;

            return DbHelperSQL.Exists(strSql.ToString(), parameters);
        }


        /// <summary>
        /// 增加一条数据
        /// </summary>
        public int Add(t_mdc_Permission model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into t_mdc_Permission(");
            strSql.Append("Name,Title,Url,Layer,RelCode,Module,Class,[Order],ParentID,OpenMode)");
            strSql.Append(" values (");
            strSql.Append("@Name,@Title,@Url,@Layer,@RelCode,@Module,@Class,@Order,@ParentID,@OpenMode)");
            strSql.Append(";select @@IDENTITY");
            SqlParameter[] parameters = {
					new SqlParameter("@Name", SqlDbType.VarChar,50),
					new SqlParameter("@Title", SqlDbType.VarChar,50),
					new SqlParameter("@Url", SqlDbType.VarChar,255),
					new SqlParameter("@Layer", SqlDbType.Int,4),
					new SqlParameter("@RelCode", SqlDbType.VarChar,50),
					new SqlParameter("@Module", SqlDbType.VarChar,50),
					new SqlParameter("@Class", SqlDbType.VarChar,50),
					new SqlParameter("@Order", SqlDbType.Int,4),
					new SqlParameter("@ParentID", SqlDbType.Int,4),
					new SqlParameter("@OpenMode", SqlDbType.VarChar,50)};
            parameters[0].Value = model.Name;
            parameters[1].Value = model.Title;
            parameters[2].Value = model.Url;
            parameters[3].Value = model.Layer;
            parameters[4].Value = model.RelCode;
            parameters[5].Value = model.Module;
            parameters[6].Value = model.Class;
            parameters[7].Value = model.Order;
            parameters[8].Value = model.ParentID;
            parameters[9].Value = model.OpenMode;

            object obj = DbHelperSQL.GetSingle(strSql.ToString(), parameters);
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 更新一条数据
        /// </summary>
        public bool Update(t_mdc_Permission model)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("update t_mdc_Permission set ");
            strSql.Append("Name=@Name,");
            strSql.Append("Title=@Title,");
            strSql.Append("Url=@Url,");
            strSql.Append("Layer=@Layer,");
            strSql.Append("RelCode=@RelCode,");
            strSql.Append("Module=@Module,");
            strSql.Append("Class=@Class,");
            strSql.Append("Order=@Order,");
            strSql.Append("ParentID=@ParentID,");
            strSql.Append("OpenMode=@OpenMode");
            strSql.Append(" where Id=@Id");
            SqlParameter[] parameters = {
					new SqlParameter("@Name", SqlDbType.VarChar,50),
					new SqlParameter("@Title", SqlDbType.VarChar,50),
					new SqlParameter("@Url", SqlDbType.VarChar,255),
					new SqlParameter("@Layer", SqlDbType.Int,4),
					new SqlParameter("@RelCode", SqlDbType.VarChar,50),
					new SqlParameter("@Module", SqlDbType.VarChar,50),
					new SqlParameter("@Class", SqlDbType.VarChar,50),
					new SqlParameter("@Order", SqlDbType.Int,4),
					new SqlParameter("@ParentID", SqlDbType.Int,4),
					new SqlParameter("@OpenMode", SqlDbType.VarChar,50),
					new SqlParameter("@Id", SqlDbType.Int,4)};
            parameters[0].Value = model.Name;
            parameters[1].Value = model.Title;
            parameters[2].Value = model.Url;
            parameters[3].Value = model.Layer;
            parameters[4].Value = model.RelCode;
            parameters[5].Value = model.Module;
            parameters[6].Value = model.Class;
            parameters[7].Value = model.Order;
            parameters[8].Value = model.ParentID;
            parameters[9].Value = model.OpenMode;
            parameters[10].Value = model.Id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除一条数据
        /// </summary>
        public bool Delete(int Id)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from t_mdc_Permission ");
            strSql.Append(" where Id=@Id");
            SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
            parameters[0].Value = Id;

            int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 批量删除数据
        /// </summary>
        public bool DeleteList(string Idlist)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete from t_mdc_Permission ");
            strSql.Append(" where Id in (" + Idlist + ")  ");
            int rows = DbHelperSQL.ExecuteSql(strSql.ToString());
            if (rows > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public t_mdc_Permission GetModel(int Id)
        {

            StringBuilder strSql = new StringBuilder();
            strSql.Append("select  top 1 Id,Name,Title,Url,Layer,RelCode,Module,Class,[Order],ParentID,OpenMode from t_mdc_Permission ");
            strSql.Append(" where Id=@Id");
            SqlParameter[] parameters = {
					new SqlParameter("@Id", SqlDbType.Int,4)
			};
            parameters[0].Value = Id;

            t_mdc_Permission model = new t_mdc_Permission();
            DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public t_mdc_Permission DataRowToModel(DataRow row)
        {
            t_mdc_Permission model = new t_mdc_Permission();
            if (row != null)
            {
                if (row["Id"] != null && row["Id"].ToString() != "")
                {
                    model.Id = int.Parse(row["Id"].ToString());
                }
                if (row["Name"] != null)
                {
                    model.Name = row["Name"].ToString();
                }
                if (row["Title"] != null)
                {
                    model.Title = row["Title"].ToString();
                }
                if (row["Url"] != null)
                {
                    model.Url = row["Url"].ToString();
                }
                if (row["Layer"] != null && row["Layer"].ToString() != "")
                {
                    model.Layer = int.Parse(row["Layer"].ToString());
                }
                if (row["RelCode"] != null)
                {
                    model.RelCode = row["RelCode"].ToString();
                }
                if (row["Module"] != null)
                {
                    model.Module = row["Module"].ToString();
                }
                if (row["Class"] != null)
                {
                    model.Class = row["Class"].ToString();
                }
                if (row["Order"] != null && row["Order"].ToString() != "")
                {
                    model.Order = int.Parse(row["Order"].ToString());
                }
                if (row["ParentID"] != null && row["ParentID"].ToString() != "")
                {
                    model.ParentID = int.Parse(row["ParentID"].ToString());
                }
                if (row["OpenMode"] != null)
                {
                    model.OpenMode = row["OpenMode"].ToString();
                }
            }
            return model;
        }

        /// <summary>
        /// 获得数据列表
        /// </summary>
        public DataSet GetList(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select Id,Name,Title,Url,Layer,RelCode,Module,Class,[Order],ParentID,OpenMode ");
            strSql.Append(" FROM t_mdc_Permission ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获得前几行数据
        /// </summary>
        public DataSet GetList(int Top, string strWhere, string filedOrder)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ");
            if (Top > 0)
            {
                strSql.Append(" top " + Top.ToString());
            }
            strSql.Append(" Id,Name,Title,Url,Layer,RelCode,Module,Class,[Order],ParentID,OpenMode ");
            strSql.Append(" FROM t_mdc_Permission ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            strSql.Append(" order by " + filedOrder);
            return DbHelperSQL.Query(strSql.ToString());
        }

        /// <summary>
        /// 获取记录总数
        /// </summary>
        public int GetRecordCount(string strWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select count(1) FROM t_mdc_Permission ");
            if (strWhere.Trim() != "")
            {
                strSql.Append(" where " + strWhere);
            }
            object obj = DbHelperSQL.GetSingle(strSql.ToString());
            if (obj == null)
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(obj);
            }
        }
        /// <summary>
        /// 分页获取数据列表
        /// </summary>
        public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("SELECT * FROM ( ");
            strSql.Append(" SELECT ROW_NUMBER() OVER (");
            if (!string.IsNullOrEmpty(orderby.Trim()))
            {
                strSql.Append("order by T." + orderby);
            }
            else
            {
                strSql.Append("order by T.Id desc");
            }
            strSql.Append(")AS Row, T.*  from t_mdc_Permission T ");
            if (!string.IsNullOrEmpty(strWhere.Trim()))
            {
                strSql.Append(" WHERE " + strWhere);
            }
            strSql.Append(" ) TT");
            strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
            return DbHelperSQL.Query(strSql.ToString());
        }

        #endregion  BasicMethod

        #region  ExtensionMethod
        public List<t_mdc_Permission> GetByUserId(int userId)
        {

            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT P.[ID],P.[Name],P.[Title],P.[Url],P.[Layer],P.[RelCode],P.[Module],P.[Class],P.[Order],P.[ParentID],P.[OpenMode] ");
            strSql.AppendLine("FROM [t_mdc_Permission] AS P ");
            strSql.AppendLine("INNER JOIN [t_mdc_PermissionRole] AS PR ON P.ID = PR.Permission_ID");
            strSql.AppendLine("INNER JOIN [t_mdc_Role] AS R ON R.ID = PR.Role_ID");
            strSql.AppendLine("INNER JOIN [t_mdc_RoleAccount] AS RU ON R.ID = RU.Role_ID");
            strSql.AppendLine("INNER JOIN [t_mdc_Account] AS U ON U.ID = RU.[Account_Id]");
            strSql.AppendLine("WHERE U.ID = @userId order by P.[Order] asc");

            DataTable dt = DbHelperSQL.Query(strSql.ToString(), new SqlParameter("@userId", userId)).Tables[0];
            return Helpers.ConvertHelper<t_mdc_Permission>.ConvertToList(dt);
        }

        public List<t_mdc_Permission> GetByRoleId(int roleId)
        {
            var strSql = new StringBuilder();
            strSql.AppendLine("SELECT P.[ID],P.[Name],P.[Title],P.[Url],P.[Layer],P.[RelCode],P.[Module],P.[Class],P.[Order],P.[ParentID],P.[OpenMode] ");
            strSql.AppendLine("FROM [t_mdc_Permission] AS P INNER JOIN t_mdc_PermissionRole AS B ON P.ID = B.Permission_ID ");
            strSql.AppendLine("WHERE B.Role_ID = @roleId");

            var dt = DbHelperSQL.Query(strSql.ToString(), new SqlParameter("@roleId", roleId)).Tables[0];

            return Helpers.ConvertHelper<t_mdc_Permission>.ConvertToList(dt);
        }

        public void SetPermissions(int roleid, string[] permId)
        {
            DbHelperSQL.ExecuteSql("DELETE FROM [t_mdc_PermissionRole] WHERE [Role_ID] = @roleid",
                                   new SqlParameter("@roleid", roleid));

            if (permId == null) return;

            foreach (var id in permId)
            {
                if (string.IsNullOrEmpty(id)) continue;
                DbHelperSQL.ExecuteSql(
                    "INSERT INTO [t_mdc_PermissionRole]([Permission_ID],[Role_ID])VALUES(@permid,@roleid)",
                    new[] { new SqlParameter("@permid", id), new SqlParameter("@roleid", roleid) });
            }

        }
        /// <summary>
        /// 批量导入数据到数据库
        /// </summary>
        /// <param name="table">数据源表</param>
        /// <param name="tableName">数据库表名</param>
        /// <param name="mappings">源表与数据库表的列映射关系</param>
        public void BulkCopyDataTable(DataTable table, string tableName)
        {
            var mappings = new SqlBulkCopyColumnMapping[11];
            mappings[0] = new SqlBulkCopyColumnMapping("Name", "Name");
            mappings[1] = new SqlBulkCopyColumnMapping("Title", "Title");
            mappings[2] = new SqlBulkCopyColumnMapping("Url", "Url");
            mappings[3] = new SqlBulkCopyColumnMapping("Layer", "Layer");
            mappings[4] = new SqlBulkCopyColumnMapping("RelCode", "RelCode");
            mappings[5] = new SqlBulkCopyColumnMapping("Module", "Module");
            mappings[6] = new SqlBulkCopyColumnMapping("Class", "Class");
            mappings[7] = new SqlBulkCopyColumnMapping("Order", "Order");
            mappings[8] = new SqlBulkCopyColumnMapping("ParentID", "ParentID");
            mappings[9] = new SqlBulkCopyColumnMapping("OpenMode", "OpenMode");

            BulkCopyHelper.BulkCopyDataTable(table, tableName, DbHelperSQL.connectionString, mappings);
        }
        #endregion  ExtensionMethod

    }
}